import os
import csv

def inverted(data_pth,out_pth):
    fp_movie = open(
        os.path.join(data_pth, "Movie_tag.csv"), mode="r", encoding="gbk"
    )
    fp_inverted=open(
        os.path.join(out_pth, "inverted_index.csv"), mode="w", encoding="utf-8",newline=""
    )
    fp_ids=open(
        os.path.join(out_pth, "all_ids.txt"), mode="w", encoding="utf-8",newline="\n"
    )
    # 读取正排表信息
    tag_csv=csv.reader(fp_movie)
    next(tag_csv)
    #id以及对应tags
    id_list=[]
    keywords=[]
    all_key_words=[]
    for row in tag_csv:
        #存一个所有电影id的表
        fp_ids.write(row[0])
        fp_ids.write("\n")
        
        id_list.append(row[0])
        keys=row[1].split(",")
        for key in keys:
            if key not in all_key_words:
                all_key_words.append(key)
        keywords.append(keys)
    #倒排表
    inverted_tag_list=[]
    tag_ids=[]
    inverted_id_list=[]
    #打开输出文件
    writer=csv.writer(fp_inverted)
    header=["tag","id"]
    writer.writerow(header)
    for key in all_key_words:
        inverted_tag_list.append(key)
        for i in range(len(id_list)):
            if key in keywords[i]:
                tag_ids.append(id_list[i])
        inverted_id_list.append(tag_ids)

        tag_ids_text=",".join(tag_ids)
        
        p=[key,tag_ids_text]
        writer.writerow(p)
        tag_ids=[]
    
    
    
        
    return

if __name__ == "__main__":
    pth = os.path.split(os.path.realpath(__file__))[0]
    data_pth = os.path.join(pth, "data")
    out_pth = os.path.join(pth, "output")

    inverted(data_pth,out_pth)